from typing import List, Optional
from langchain_core.messages import BaseMessage, HumanMessage, SystemMessage
from langchain_core.output_parsers import StrOutputParser
from biz.core.command.chain import get_session_history, runnable_with_history
from biz.utils.logger import logger


class SessionService:
    """会话管理服务类"""
    
    def __init__(self):
        self.output_parser = StrOutputParser()
    
    def is_new_session(self, uuid: str) -> bool:
        """判断是否为新会话"""
        try:
            session_history = get_session_history(uuid)
            return len(session_history.messages) == 0
        except Exception as e:
            logger.error(f"检查会话状态失败: {e}")
            return True
    
    def build_messages(self, question: str, prefix: Optional[str] = None, is_new: bool = True) -> List[BaseMessage]:
        """构建消息列表"""
        messages = []
        
        if is_new and prefix:
            messages.append(SystemMessage(content=prefix))
        
        messages.append(HumanMessage(content=question))
        return messages
    
    def invoke_with_history(self, question: str, uuid: str, prefix: Optional[str] = None) -> str:
        """带历史记录的调用"""
        is_new = self.is_new_session(uuid)
        messages = self.build_messages(question, prefix, is_new)
        
        try:
            response = runnable_with_history.invoke(
                messages,
                config={"configurable": {"session_id": uuid}}
            )
            
            content = self.output_parser.invoke(response)
            logger.info("\033[1;32;40m" + content + "\033[0m")
            return content
            
        except Exception as e:
            logger.error(f"会话调用失败: {e}")
            raise